package com.ruoyi.cms.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.cms.domain.Archives;
import com.ruoyi.cms.domain.ArchivesWithRownum;
import com.ruoyi.cms.domain.Category;
import com.ruoyi.cms.domain.Menu;
import com.ruoyi.cms.domain.vo.ArchivesVO;
import com.ruoyi.cms.exception.TransactionException;
import com.ruoyi.cms.mapper.ArchivesMapper;
import com.ruoyi.cms.mapper.CategoryMapper;
import com.ruoyi.cms.service.ArchivesService;
import com.ruoyi.cms.service.CategoryService;
import com.ruoyi.cms.util.SearchEntity;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 文章管理处理类
 * @author LIGW
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ArchivesServiceImpl implements ArchivesService {

	@Autowired
	private ArchivesMapper archivesMapper;
    @Autowired
    private CategoryMapper categoryMapper;
	/**
	 * 添加
	 * @throws TransactionException
	 */
	@Override
	public int save(Archives archives, String tableName, Map<String,Object> additional) throws TransactionException {
		int num = 0;
		try {
			num = archivesMapper.insert(archives);
			if(additional.size() > 0) {
				archivesMapper.insertAdditional(tableName, additional);
			}
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动事务回滚
			throw new TransactionException(e.getMessage());
		}
		return num;
	}

	/**
	 * 列表
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	@Override
	public TableDataInfo<Archives> queryListByPage(Archives params, PageQuery pageQuery) {
        List<Category> categories = categoryMapper.queryAll();
        Map<String,Category> categoryMap = categories.stream().collect(Collectors.toMap(Category::getId, Function.identity()));
        LambdaQueryWrapper<Archives> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Archives::getCategoryId, params.getCategoryId()).orderByDesc(Archives::getCreateTime);
        Page<Archives> page = archivesMapper.selectPage(pageQuery.build(), lqw);
        List<Archives> as = page.getRecords().stream().map(a -> {
            a.setCategoryCnName(categoryMap.get(a.getCategoryId()).getCnname());
            return a;
        }).collect(Collectors.toList());
        page.setRecords(as);
        return TableDataInfo.build(page);
	}

    /**
     * 列表
     */
    @Transactional(propagation=Propagation.NOT_SUPPORTED)
    @Override
    public PageInfo<Map<String, Object>> queryListByPage(SearchEntity params) {
        if(params.getPageNum() == null || params.getPageNum() == 0) {
            params.setPageNum(1);
        }
        if(params.getPageSize() == null || params.getPageSize() == 0) {
            params.setPageSize(10);
        }
        Map<String, Object> entity = params.getEntity();
        /**
         * 修复后台SQL注入风险
         */
        if(entity.containsKey("tableName")) {
            entity.remove("tableName");
        }
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<Map<String, Object>> list = archivesMapper.queryListByPage(entity);
        PageInfo<Map<String, Object>> page = new PageInfo<Map<String, Object>>(list);
        return page;
    }

	/**
	 * 根据标签名查询文章
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	@Override
	public List<Archives> queryListByTagName(String tagName) {
		return archivesMapper.queryListByTagName(tagName);
	}

	@Override
	public int saveAdditional(String tableName, Map<String, Object> params) {
		return archivesMapper.insertAdditional(tableName, params);
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	@Override
	public Map<String,Object> queryArticleById(Map<String, Object> params) {
		return archivesMapper.queryArticleById(params);
	}

	@Override
	public int update(Archives archives,String tableName, Map<String,Object> additional,String fid) throws TransactionException {
		int num = 0;
		try {
			num = archivesMapper.updateById(archives);
			if(additional.size() > 0) {
				archivesMapper.updateAdditional(tableName, additional,fid);
			}
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动事务回滚
			throw new TransactionException(e.getMessage());
		}
		return num;
	}

	@Override
	public int delete(String id,Map<String,Object> params) throws TransactionException {
		int num = 0;
		try {
			num= archivesMapper.deleteById(id);

			if(params.containsKey("id") && params.get("id") != null && StrUtil.isNotBlank(params.get("id").toString())) {
				archivesMapper.deleteAdditional(params);
			}
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动事务回滚
			throw new TransactionException(e.getMessage());
		}
		return num;
	}

	@Override
	public int updateTagById(Archives article) {
		return archivesMapper.updateTagByPrimaryKey(article);
	}

	@Override
	public int updateAdditional(String tableName, Map<String, Object> additional,String fid) {
		return archivesMapper.updateAdditional(tableName, additional,fid);
	}

	@Override
	public int deleteAdditional(Map<String, Object> params) {
		return archivesMapper.deleteAdditional(params);
	}

	@Override
	public Archives selectByPrimaryKey(String id) {
		return this.archivesMapper.selectById(id);
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	@Override
	public TableDataInfo<ArchivesVO> queryListByKeywords(Archives params, PageQuery pageQuery) {
        LambdaQueryWrapper<Archives> lqw = new LambdaQueryWrapper<>();
        Page<Archives> page = archivesMapper.selectVoPage(pageQuery.build(), lqw);
        return null;
	}

	@Override
	public ArchivesWithRownum queryArticleRowNum(Map<String, Object> params) {
		return this.archivesMapper.queryArticleRowNum(params);
	}

	@Override
	public List<Archives> queryListByTop() {
		return archivesMapper.queryListByTop();
	}

	@Override
	public int update(Archives archives) {
		return archivesMapper.updateById(archives);
	}

	@Override
	public List<Archives> queryAll(String id) {
		return archivesMapper.queryAll(id);
	}
}
